package com.medical.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.system.converter.UserConverter;
import com.medical.system.mapper.SysUserMapper;
import com.medical.system.model.bo.UserBO;
import com.medical.system.model.bo.UserFormBO;
import com.medical.system.model.entity.SysUser;
import com.medical.system.model.query.UserPageQuery;
import com.medical.system.model.vo.UserExportVO;
import com.medical.system.model.vo.UserProfileVO;
import com.medical.system.service.SysUserRoleService;
import com.medical.system.service.SysUserService;
import com.medical.core.constant.SystemConstants;
import com.medical.system.model.form.UserForm;
import com.medical.system.model.vo.UserPageVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户业务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final UserConverter userConverter;
    private final PasswordEncoder passwordEncoder;
    private final SysUserRoleService userRoleService;

    @Override
    public IPage<UserPageVO> getUserPage(UserPageQuery queryParam) {
        Page<UserBO> page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());
        // 查询数据
        Page<UserBO> userBoPage = baseMapper.getUserPage(page, queryParam);
        //实体转换
        return userConverter.bo2Vo(userBoPage);
    }

    @Override
    public boolean saveUser(UserForm userForm) {
        String username = userForm.getUsername();
        Long count = count(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        Assert.isTrue(count == 0, "用户名已存在");
        // 实体转换 form->entity
        SysUser sysUser = userConverter.form2Entity(userForm);
        //设置默认密码
        String password = passwordEncoder.encode(SystemConstants.DEFAULT_PASSWORD);
        sysUser.setPassword(password);
        boolean result = save(sysUser);
        if (result) {
            //如果用户保存成功，保存用户角色
            userRoleService.saveUserRoles(sysUser.getId(), userForm.getRoleIds());
        }
        return result;
    }

    @Override
    public UserForm getUserFormData(Long userId) {
        UserFormBO userFormBO = baseMapper.getUserDetail(userId);
        return userConverter.bo2Form(userFormBO);
    }

    @Override
    public boolean updateUser(Long userId, UserForm userForm) {
        Long count = count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, userForm.getUsername())
                .ne(SysUser::getId, userId));
        Assert.isTrue(count == 0, "用户名已存在");
        SysUser sysUser = userConverter.form2Entity(userForm);
        boolean result = updateById(sysUser);
        if (result) {
            userRoleService.saveUserRoles(userForm.getId(), userForm.getRoleIds());
        }
        return result;
    }

    @Override
    public boolean deleteUsers(String idsStr) {
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return removeByIds(ids);
    }

    @Override
    public boolean updatePassword(Long userId, String password) {
        return update(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getId, userId)
                .set(SysUser::getPassword, password));
    }

    @Override
    public List<UserExportVO> listExportUsers(UserPageQuery queryParams) {
        return baseMapper.listExportUsers(queryParams);
    }

    @Override
    public UserProfileVO getUserProfile() {
//        Long userId = SecurityUtils.getUserId();
//        UserProfileBO userProfileBO = baseMapper.getUserProfile(userId);
//        return userConverter.userProfileBo2Vo(userProfileBO);
        return null;
    }
}
